package demo.jdk.features.jdk8;

import demo.jdk.features.Base.BankAccountWithStampedLock;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author Ranchoz  2018/9/10 8:53
 **/
public class StampedLockExample {

	@Test
	public void bench() throws InterruptedException {
		BankAccountWithStampedLock account = new BankAccountWithStampedLock();
		ExecutorService pool = Executors.newCachedThreadPool();
		List<Callable<Double>> callables = IntStream.range(1, 5)
				.mapToObj(x -> (Callable<Double>) () -> {
//                    if (x % 2 == 0) {
//                        return account.getBalance();
//                    } else {
//                        account.deposit(x);
//                        return 0d;
//                    }
					account.deposit(x);
					return Double.valueOf(x);
				})
				.collect(Collectors.toList());
		pool.invokeAll(callables).forEach(x -> {
			try {
				System.out.println(x.get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		});
		pool.shutdown();
		System.out.println(account.getBalance());
	}

	public static void main(String[] args) {
		List<Integer> collect = IntStream.range(1, 5).mapToObj(x -> x).collect(Collectors.toList());
		collect.forEach(System.out::println);

	}
}
